/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entities;

import bookmaker.HibernateUtil;
import com.icesoft.faces.context.effects.Effect;
import com.icesoft.faces.context.effects.Highlight;
import java.util.ArrayList;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author ALIEN
 */
public class TreeBean {

// tree default model, used as a value for the tree component
    private DefaultTreeModel model;
    private Session session;
    private boolean selected=false;
    private Market market=null;
    private Effect effect;
    private boolean binaryGame=false;

    public TreeBean() {
        // create root node with its children expanded
        DefaultMutableTreeNode treeRoot = new DefaultMutableTreeNode();
        UrlNodeUserObject rootObject = new UrlNodeUserObject(treeRoot);
        DefaultMutableTreeNode treeDisciplineLeaf;
        UrlNodeUserObject disciplineObject;
        DefaultMutableTreeNode treeLeagueLeaf;
        UrlNodeUserObject leagueObject;
        DefaultMutableTreeNode treeGameLeaf;
        UrlNodeUserObject gameObject;
        DefaultMutableTreeNode treeMarketLeaf;
        UrlNodeUserObject marketObject;


        rootObject.setText("Menu");
        //rootObject.setUrl("");
        rootObject.setExpanded(true);
        treeRoot.setUserObject(rootObject);
        // model is accessed by by the ice:tree component
        model = new DefaultTreeModel(treeRoot);

        try {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from Discipline");
            //Query q = session.createQuery("select l from League l where l.id ="+id);

            ArrayList temp = (ArrayList) q.list();
            for (Object o : temp) {
                treeDisciplineLeaf = new DefaultMutableTreeNode();
                disciplineObject = new UrlNodeUserObject(treeDisciplineLeaf);
                disciplineObject.setText(((Discipline) o).getName());
                //disciplineObject.setUrl("");
                disciplineObject.setExpanded(false);
                disciplineObject.setBranchContractedIcon(((Discipline)o).getImage_path());
                disciplineObject.setBranchExpandedIcon(((Discipline)o).getImage_path());
                //disciplineObject.setLeaf(true);
                treeDisciplineLeaf.setUserObject(disciplineObject);
                treeRoot.add(treeDisciplineLeaf);

                Query q2 = session.createQuery("select distinct l from League l left join fetch l.discipline as disc where disc.id =" + ((Discipline) o).getId());
                ArrayList tempLeagues = (ArrayList) q2.list();
                for (Object l : tempLeagues) {
                    treeLeagueLeaf = new DefaultMutableTreeNode();
                    leagueObject = new UrlNodeUserObject(treeLeagueLeaf);
                    leagueObject.setText(((League) l).getName());
                    //leagueObject.setUrl("");
                    leagueObject.setExpanded(false);
                    //disciplineObject.setLeaf(true);
                    treeLeagueLeaf.setUserObject(leagueObject);
                    treeDisciplineLeaf.add(treeLeagueLeaf);

                    Query q3 = session.createQuery("select distinct g from Game g left join fetch g.league as league where league.id =" + ((League) l).getId());
                    ArrayList tempGames = (ArrayList) q3.list();
                    for (Object g : tempGames) {
                        treeGameLeaf = new DefaultMutableTreeNode();
                        gameObject = new UrlNodeUserObject(treeGameLeaf);
                        gameObject.setText(((Game) g).getName());
                        //gameObject.setUrl("");
                        gameObject.setExpanded(false);
                        //disciplineObject.setLeaf(true);
                        treeGameLeaf.setUserObject(gameObject);
                        treeLeagueLeaf.add(treeGameLeaf);

                        Query q4 = session.createQuery("select distinct m from Market m left join fetch m.game as game where game.id =" + ((Game) g).getId());
                        ArrayList tempMarkets = (ArrayList) q4.list();
                        for (Object m : tempMarkets) {
                            treeMarketLeaf = new DefaultMutableTreeNode();
                            marketObject = new UrlNodeUserObject(treeMarketLeaf);
                            String txt = "";
                            txt+=((Market) m).getOdds_home()+" - ";
                            if (((Market) m).getOdds_draw() != 0)
                                txt+=((Market) m).getOdds_draw()+" - ";
                            txt+=((Market) m).getOdds_away();
                            marketObject.setText(txt);
                            marketObject.setId(((Market)m).getId());
                            //marketObject.setUrl("");
                            marketObject.setLeafIcon(((Market) m).getSpecificMarket().getImage_path());
                            //marketObject.setExpanded(false);
                            marketObject.setLeaf(true);
                            treeMarketLeaf.setUserObject(marketObject);
                            treeGameLeaf.add(treeMarketLeaf);
                        }
                    }
                }
            }

            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    public void nodeSelected(ActionEvent event) {
        // get employee id
        String marketId = (String)FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id");
        long id = Long.parseLong(marketId);

        if(id==-1){
            setSelected(false);
            Betslip b = (Betslip)FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("betslip");
            b.setSelected(false);
            return;
        }
        setEffect(new Highlight());
        getEffect().setTransitory(false);
        getEffect().setSubmit(true);

        setSelected(true);
        // find employee node by id and make it the selected node
        try {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("select distinct m from Market m where m.id =" +id);
            setMarket((Market) q.list().get(0));
            if(market.getOdds_draw()<=1)
                setBinaryGame(true);
            else
                setBinaryGame(false);

            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    /**
     * Gets the tree's default model.
     *
     * @return tree model.
     */
    public DefaultTreeModel getModel() {
        return model;
    }

    public void checkChanged(ValueChangeEvent event) {
        System.out.println("checkboxed selected " + event.getComponent().getId());
    }

    /**
     * @return the selected
     */
    public boolean isSelected() {
        return selected;
    }

    /**
     * @param selected the selected to set
     */
    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    /**
     * @return the market
     */
    public Market getMarket() {
        return market;
    }

    /**
     * @param market the market to set
     */
    public void setMarket(Market market) {
        this.market = market;
    }

    /**
     * @return the effect
     */
    public Effect getEffect() {
        return effect;
    }

    /**
     * @param effect the effect to set
     */
    public void setEffect(Effect effect) {
        this.effect = effect;
    }

    /**
     * @return the binaryGame
     */
    public boolean isBinaryGame() {
        return binaryGame;
    }

    /**
     * @param binaryGame the binaryGame to set
     */
    public void setBinaryGame(boolean binaryGame) {
        this.binaryGame = binaryGame;
    }
}
